package jianzhiOffer;

import javafx.print.Collation;

import java.util.*;

//剑指 Offer 32 - III. 从上到下打印二叉树 III
public class Num32_III_levelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        //保存返回值
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        //存根节点
        queue.offer(root);
        boolean temp = true;
        while (! queue.isEmpty()){
            int size = queue.size();
            //存储每层元素
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null){
                    queue.offer(node.left);
                }
                if (node.right != null){
                    queue.offer(node.right);
                }
            }
            if (!temp){
                Collections.reverse(list);
                ret.add(list);
                temp = true;
            }else {
                ret.add(list);
                temp = false;
            }


        }
        return ret;

    }
}
